<template>
  <view class="popup-mask" v-if="show" @tap="handleMaskClick">
    <view class="leaving-message" @tap.stop>
      <view class="message-header">
        <text class="header-title">在线留言</text>
        <view class="close-btn" @tap="handleClose">
          <text class="close-icon">×</text>
        </view>
      </view>

      <scroll-view scroll-y class="message-form">
        <view class="form-item">
          <text class="form-label required">留言内容</text>
          <textarea
            v-model="formData.messageContent"
            class="form-textarea "
            placeholder="请输入留言内容"
            :maxlength="200"
            @blur="validateField('messageContent')"
          />
          <text v-if="errors.messageContent" class="error-tip">{{ errors.messageContent }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">姓名</text>
          <input
            v-model="formData.customerName"
            class="form-input"
            type="text"
            placeholder="请输入姓名"
            @blur="validateField('customerName')"
          />
          <text v-if="errors.customerName" class="error-tip">{{ errors.customerName }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">手机号</text>
          <input
            v-model="formData.phone"
            class="form-input"
            type="number"
            placeholder="请输入手机号"
            @blur="validateField('phone')"
          />
          <text v-if="errors.phone" class="error-tip">{{ errors.phone }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">邮箱</text>
          <input
            v-model="formData.email"
            class="form-input"
            type="text"
            placeholder="请输入邮箱"
            @blur="validateField('email')"
          />
          <text v-if="errors.email" class="error-tip">{{ errors.email }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">QQ</text>
          <input
            v-model="formData.qqNumber"
            class="form-input"
            type="number"
            placeholder="请输入QQ"
            @blur="validateField('qqNumber')"
          />
          <text v-if="errors.qqNumber" class="error-tip">{{ errors.qqNumber }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">公司名称</text>
          <input
            v-model="formData.company"
            class="form-input"
            type="text"
            placeholder="请输入公司名称"
            @blur="validateField('company')"
          />
          <text v-if="errors.company" class="error-tip">{{ errors.company }}</text>
        </view>
      </scroll-view>

      <view class="message-footer">
        <button 
          class="footer-btn btn-cancel" 
          @tap="handleClose"
          :hover-class="'btn-hover'"
        >取消</button>
        <button 
          class="footer-btn btn-submit" 
          @tap="handleSubmit"
          :loading="submitting"
          
          :hover-class="'btn-hover'"
        >提交</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { savekfLeaveMessage } from '../api';
import store from "../utils/store";
import dayjs from "dayjs";
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:show', 'submit']);

// 表单数据
const formData = reactive({
  messageContent: '',
  customerName: '',
  phone: '',
  email: '',
  qqNumber: '',
  company: ''
});

// 错误信息
const errors = reactive({
  messageContent: '',
  customerName: '',
  phone: '',
  email: '',
  qqNumber: '',
  company: ''
});

// 验证规则
const rules = {
  messageContent: [
    { required: true, message: '请输入留言内容' }
  ],
  customerName: [
    { required: true, message: '请输入姓名' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
  ],
  email: [
    { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱' }
  ],
  qqNumber: [
    { pattern: /^\d{5,11}$/, message: '请输入正确的QQ号' }
  ]
};

const submitting = ref(false);

// 是否有错误
const hasErrors = computed(() => {
  return Object.values(errors).some(error => error !== '');
});

// 表单是否有效
const isFormValid = computed(() => {
  return formData.messageContent && formData.customerName && formData.phone;
});

// 验证单个字段
const validateField = (field: string) => {
  const value = formData[field];
  const fieldRules = rules[field];
  
  if (!fieldRules) {
    errors[field] = '';
    return true;
  }

  for (const rule of fieldRules) {
    if (rule.required && !value) {
      errors[field] = rule.message;
      return false;
    }
    if (rule.pattern && value && !rule.pattern.test(value)) {
      errors[field] = rule.message;
      return false;
    }
  }
  
  errors[field] = '';
  return true;
};

// 验证所有字段
const validateForm = () => {
  let isValid = true;
  Object.keys(rules).forEach(field => {
    if (!validateField(field)) {
      isValid = false;
    }
  });
  return isValid;
};

// 点击遮罩
const handleMaskClick = () => {
  handleClose();
};

// 关闭弹窗
const handleClose = () => {
  // 清空错误信息
  Object.keys(errors).forEach(key => {
    errors[key] = '';
  });
  emit('update:show', false);
};

// 提交表单
const handleSubmit = async () => {
  // 验证表单
  if (!validateForm()) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }
  
  try {
    submitting.value = true;
    // 提交数据
    emit('submit', { ...formData });

    const currentUser = store.getCurrentUser();
    const pam = { 
      ...formData,
      customerId: currentUser.uid,
      messageStatus: 'waitAssign',
      messageTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
     }

    const { success } = await savekfLeaveMessage(pam);
    if (!success) throw new Error('提交失败');
    // 清空表单
    Object.keys(formData).forEach(key => {
      formData[key] = '';
    });
    // 关闭弹窗
    handleClose();
    uni.showToast({
      title: '提交成功',
      icon: 'success'
    });
  } catch (error) {
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    });
    console.error(error);
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped lang="scss">
.popup-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.leaving-message {
  width: 700rpx;
  background-color: #fff;
  border-radius: 20rpx;
  position: relative;
  animation: popIn 0.3s ease;
  box-sizing: border-box;
  z-index: 999;
}

@keyframes popIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
  
  .header-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .close-btn {
    padding: 10rpx;
    
    .close-icon {
      font-size: 40rpx;
      color: #999;
      line-height: 1;
    }
  }
}

.message-form {
  padding: 30rpx;
  max-height: 60vh;
  box-sizing: border-box;
  max-width: 100%;
  overflow: hidden;
  
  .form-item {
    margin-bottom: 30rpx;
    box-sizing: border-box;
    
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;

      &.required {
        &::before {
          content: '*';
          color: #ff4d4f;
          margin-right: 4rpx;
        }
      }
    }
    
    .form-input {
      height: 80rpx;
      border-bottom: 2rpx solid #eee;
      font-size: 28rpx;
      padding: 0 20rpx;
    }
    
    .form-textarea {
      height: 200rpx;
      border: 2rpx solid #eee;
      background-color: #eee;
      border-radius: 8rpx;
      font-size: 28rpx;
      padding: 20rpx;
    }
  }
}

.message-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  border-top: 2rpx solid #f5f5f5;
  
  .footer-btn {
    width: 160rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    border-radius: 8rpx;
    font-size: 28rpx;
    
    &.btn-cancel {
      background: #dfdfdf;
      color: #666;
    }
    
    &.btn-submit {
      background: #ffc549;
      color: #fff;
    }
    
    &.btn-hover {
      opacity: 0.8;
    }
  }
}

.form-item {
  margin-bottom: 30rpx;
  box-sizing: border-box;
  
  .error-tip {
    font-size: 24rpx;
    color: #ff4d4f;
    margin-top: 8rpx;
  }
}

.footer-btn {
  &.btn-submit {
    &:disabled {
      background: #ccc;
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}
</style>
